<script setup lang="ts">
import { reactive, ref, onUnmounted } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import Taro, { showToast, showLoading, hideLoading, getCurrentInstance } from '@tarojs/taro';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useGetAuthInfo } from '@/hooks';
import { storeToRefs } from 'pinia';
// import { localStg } from '@/utils';
// import { useImage } from '@/hooks';
// const { imageUrl } = useNurseStore()

const {
    router: {
        params: { type }
    }
}: any = getCurrentInstance();

const { getHospitalList } = use_hospital_dept_bed();

// definePageConfig({
//     navigationBarTitleText: '个人信息'
// });
Taro.setNavigationBarTitle({
    title: type == 1 ? '个人信息设置' : '个人信息新增'
});

onUnmounted(() => useGetAuthInfo());

const { edit } = useNurseUser();

const { getProvince, getCity, getCountry } = useAddrStore();

const { nurseUser } = storeToRefs(useAuthStore());

const formData = ref<any>(nurseUser);
console.log("formData.value ===", formData.value)

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

// const token = localStg.get('token');

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });
    const { error } = await edit({ ...formData.value });
    hideLoading();
    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
    }
};
// const headers = ref({
//     'Content-Type': 'multipart/form-data',
//     'X-Access-Token': token
// })

// function uploadDelete() {
//     formData.value.avatar = undefined
// }

// function uploadSuccess({ data }: any) {

//     const result = JSON.parse(data.data)

//     const { message, success } = result

//     if (success && message) formData.value.avatar = message

// }
const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];

        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

const hospitalModule = reactive({
    show: false,
    showHospital: () => {
        hospitalModule.show = !hospitalModule.show;
        if (hospitalModule.show) {
            formData.value.defaultHospital = '';
            formData.value.defaultHospitalName = '';
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.defaultHospital = item.key;
        formData.value.defaultHospitalName = item.title;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getHospitalList(pid);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="type == 1 ? '个人信息设置' : '个人信息新增'" showLeft /> -->
        <view class="w-375px flex-col-center">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <nut-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请填写姓名' }]">
                        <nut-input v-model="formData.name" placeholder="请输入姓名" type="text" />
                    </nut-form-item>

                    <nut-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input :readonly="formData.isPhone == 1" v-model="formData.phone" placeholder="请输入联系电话" type="text" />
                    </nut-form-item>
                    <!-- <nut-form-item class=" flex-center" label="头像" prop="name"
                        :rules="[{ required: false, message: '' }]">
                        <nut-uploader :multiple="false" @success="uploadSuccess" @delete="uploadDelete"
                            :headers="headers" :maximize="1024 * 2000" :url="`${imageUrl}/upload?biz=weapp`"
                            maximum="1">
                            <template #default>
                                <nut-avatar size="large">
                                    <img v-if="nurseUser.avatar" :src="useImage(nurseUser.avatar)" />
                                    <view v-else class=" m-t-2 w-90 h-90 bg-primary i-local-default_img" />
                                </nut-avatar></template>
</nut-uploader>
</nut-form-item> -->
                    <nut-form-item label="性别" prop="sex" :rules="[{ required: false, message: '请选择性别' }]">
                        <NutRadioGroup v-model="formData.sex" direction="horizontal">
                            <nut-radio :disabled="false" label="1">男</nut-radio>
                            <nut-radio :disabled="false" label="2">女</nut-radio>
                        </NutRadioGroup>
                    </nut-form-item>
                    <nut-form-item label="地区" prop="areaName">
                        <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" type="text"
                            @click="areaModule.showArea" />
                        <nut-address v-model:visible="areaModule.show" :province="areaModule.province"
                            :city="areaModule.city" :country="areaModule.country" :town="areaModule.town"
                            custom-address-title="请选择所在地区" @change="areaModule.onChange"></nut-address>
                    </nut-form-item>
                    <nut-form-item label="详细地址" prop="address">
                        <nut-input v-model="formData.address" placeholder="请输入详细地址" type="text" />
                    </nut-form-item>

                    <nut-form-item label="默认医院" prop="defaultHospitalName" :rules="[{ required: false, message: '' }]">
                        <nut-input v-model="formData.defaultHospitalName" readonly placeholder="请选择默认医院" type="text"
                            @click="hospitalModule.showHospital" />
                        <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
                            :title="formData.defaultHospitalName" @change="hospitalModule.onChange" />
                    </nut-form-item>

                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
    </basic-layout>
</template>
